package org.ala.tiktools.rpc.netty.handler;

import java.util.function.Consumer;

import org.ala.tiktools.rpc.client_server.service.RpcServiceExecutor;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;

/**
 * @author ala
 * @date 2025-04-09 11:30
 */
public class RpcChannelInitializer extends ChannelInitializer<Channel> {


    /**
     * 业务执行器
     */
    protected RpcServiceExecutor serviceExecutor;
    /**
     * 是否主动发ping
     */
    protected boolean ping;
    /**
     * 是否检测登录
     */
    protected boolean login;
    /**
     * 注册到EventLoop完成，和从EventLoop注销的回调
     * <p>  此时分别对应channel的新生和死亡
     */
    protected Consumer<Channel> registered, unRegistered;


    /**
     * 
     * @param serviceExecutor	业务执行器
     * @param ping				是否主动发ping
     * @param login				是否加载登录拦截器
     * @param registered		eventLoop绑定回调
     * @param unRegistered		eventLoop解绑回调
     */
    public RpcChannelInitializer(RpcServiceExecutor serviceExecutor, boolean ping, boolean login, Consumer<Channel> registered, Consumer<Channel> unRegistered) {
        this.serviceExecutor = serviceExecutor;
        this.ping = ping;
        this.login = login;
        this.registered = registered;
        this.unRegistered = unRegistered;
    }


    @Override
    protected void initChannel(Channel ch) throws Exception {
        //  追加生命周期监听
        ch.pipeline().addLast(new RpcChannellifecycleListener(registered, unRegistered));
        //  追加解解码
        ch.pipeline().addLast(new RpcMsgDecoder());
        //  idle检测
        ch.pipeline().addLast(new RpcIdleInterceptor(ping));
        //  登录拦截器
        if (login) { ch.pipeline().addLast(new RpcLoginInterceptor()); }
        //  追加消息处理器
        ch.pipeline().addLast(new RpcMsgReadHandler(serviceExecutor));
        //  追加编码器
        ch.pipeline().addLast(new RpcMsgEncoder());
    }
}
